// 方法不匹配处理中间件

/**
 * 为路由添加方法不匹配处理
 * @param {Object} router - Express Router 实例
 */
function handleMethodNotAllowed(router) {
  // 获取路由栈中已注册的路由
  const routes = {}

  router.stack.forEach(layer => {
    if (layer.route) {
      const path = layer.route.path
      const methods = Object.keys(layer.route.methods).map(m => m.toUpperCase())

      if (!routes[path]) {
        routes[path] = []
      }
      routes[path].push(...methods)
    }
  })

  // 为每个路径添加 all 处理器
  Object.keys(routes).forEach(path => {
    const allowedMethods = [...new Set(routes[path])]

    router.all(path, (req, res) => {
      res.status(405).send({
        code: 405,
        success: false,
        message: `${req.originalUrl} 只支持 [${allowedMethods.join(', ')}] 请求，当前请求方法为 ${req.method}`,
        allowedMethods
      })
    })
  })

  return router
}

module.exports = handleMethodNotAllowed